from flask_restx import Resource
from flask import request
import pymysql
from models.database import get_db_connection
from api import ns
import traceback
from datetime import datetime, timedelta

@ns.route('/stats/<string:user_id>')
class UserStats(Resource):
    def get(self, user_id):
        """获取用户统计数据"""
        try:
            conn = get_db_connection()
            if conn is None:
                return {'status': 'error', 'message': '数据库连接失败'}, 500
            
            cursor = None
            try:
                cursor = conn.cursor(pymysql.cursors.DictCursor)
                
                # 检查用户是否存在
                cursor.execute("SELECT * FROM user WHERE user_id = %s", (user_id,))
                if not cursor.fetchone():
                    return {'status': 'error', 'message': '用户不存在'}, 404
                
                # 获取总生成数
                cursor.execute(
                    "SELECT COUNT(*) as total FROM history WHERE user_id = %s",
                    (user_id,)
                )
                total_generated = cursor.fetchone()['total']
                
                # 获取今日生成数
                today = datetime.now().date()
                cursor.execute(
                    """
                    SELECT COUNT(*) as today 
                    FROM history 
                    WHERE user_id = %s AND DATE(created_at) = %s
                    """,
                    (user_id, today)
                )
                today_generated = cursor.fetchone()['today']
                
                # 获取收藏数
                cursor.execute(
                    "SELECT COUNT(*) as favorites FROM favorite WHERE user_id = %s",
                    (user_id,)
                )
                favorites = cursor.fetchone()['favorites']
                
                # 获取分享数
                cursor.execute(
                    "SELECT COUNT(*) as shares FROM share WHERE user_id = %s",
                    (user_id,)
                )
                shares = cursor.fetchone()['shares']
                
                return {
                    'status': 'success',
                    'data': {
                        'totalGenerated': total_generated,
                        'todayGenerated': today_generated,
                        'favorites': favorites,
                        'shares': shares
                    }
                }
                
            except pymysql.Error as e:
                print(f"Database error: {str(e)}")
                return {'status': 'error', 'message': f'数据库错误: {str(e)}'}, 500
                
            finally:
                if cursor:
                    cursor.close()
                if conn:
                    conn.close()
                    
        except Exception as e:
            print(f"Error fetching stats: {str(e)}")
            print(traceback.format_exc())
            return {'status': 'error', 'message': f'获取统计数据失败: {str(e)}'}, 500 